package com.rxcloud.securityoauth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rxcloud.securityoauth.entity.SysPermission;
import com.rxcloud.securityoauth.entity.SysUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.jnlp.PersistenceService;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private   SysPermissionService sysPermissionService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
          sysUserLambdaQueryWrapper.eq(SysUser::getName,s);
          SysUser user = sysUserService.getOne(sysUserLambdaQueryWrapper);
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        if(ObjectUtils.isEmpty(user) ||  user !=null){
            System.err.println("sysUser=============="+user);
            //获取用户的授权
            List<SysPermission> permissionList = sysPermissionService.findByAdminUserId(user.getId());
            if(permissionList.size()>0){
                for (SysPermission p:permissionList) {
                    if(ObjectUtils.isNotEmpty(p) && p.getName() !=null){
                        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+p.getName());
                        grantedAuthorityList.add(grantedAuthority);
                    }
                }
            }
        }
        System.err.println("grantedAuthorityList=============="+grantedAuthorityList);
        return new User(user.getName(), user.getPassword(), grantedAuthorityList);
    }
}
